package com.example.day03.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class VideoEncodingExample {

    public static void main(String[] args) {
        String inputFilePath = "F:\\BaiduNetdiskDownload\\bvadio\\ffmpeg\\input.mp4";
        String outputBasePath = "F:\\BaiduNetdiskDownload\\bvadio\\ffmpeg\\out";

        // 分段时间为 10 秒
        int segmentDuration = 10;

        encodeAndSegmentVideo(inputFilePath, outputBasePath, segmentDuration);
    }

    private static void encodeAndSegmentVideo(String inputFilePath, String outputBasePath, int segmentDuration) {
        List<String> command = new ArrayList<>();
        command.add("ffmpeg");
        command.add("-i");
        command.add(inputFilePath);
        command.add("-c:v");
        command.add("libx264");
        command.add("-c:a");
        command.add("aac");
        command.add("-hls_time");
        command.add(Integer.toString(segmentDuration));
        command.add("-hls_list_size");
        command.add("0"); // 无限分段
        command.add(outputBasePath + "output.m3u8");

        try {
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            Process process = processBuilder.start();
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println("Video encoding and segmentation completed successfully.");
            } else {
                System.err.println("Failed to encode and segment video. Exit code: " + exitCode);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}